<template>
  <!-- 工作中心的新增 -->
  <div style="background-color: #fff" class="demo-collapse">
    <el-collapse accordion>
      <el-collapse-item name="1">
        <template #title>
          <a @click="router.push('/WorkCenters/WorkCenterShowHtml')">{{
            fanhui
          }}</a>
          &emsp; | &emsp;
          <span
            style="
              text-align: center;
              color: dimgray;
              font-size: 20px;
              font-weight: 600;
              color: #009688;
            "
            >工作中心</span
          >
          <el-icon class="header-icon">
            <info-filled />
          </el-icon>
        </template>
        <div style="height: 250px">
          <el-row
            :gutter="20"
            style="width: 1000px; margin-top: 0px; margin-left: 20px"
          >
            <el-col :span="6"
              ><div class="grid-content ep-bg-purple" />
              工作中心编码
              <el-input
                style="width: 520px"
                v-model="WorkCenterForm.workCenterNum"
                :readonly="isno"
              />
            </el-col>
            <el-col :span="6" style="margin-left: 370px"
              ><div class="grid-content ep-bg-purple" />
              工作中心名称<el-input
                style="width: 520px"
                v-model="WorkCenterForm.workCenterName"
              />
            </el-col>
          </el-row>
          <el-row
            :gutter="20"
            style="width: 1000px; margin-top: 10px; margin-left: 20px"
          >
            <el-col :span="6"
              ><div class="grid-content ep-bg-purple" />
              工作中心类型<el-select
                style="width: 520px"
                v-model="WorkCenterForm.workCenterType"
              >
                <el-option label="请选择" value="请选择" />
                <el-option label="加工组" value="加工组" />
                <el-option label="生产组" value="生产组" />
              </el-select>
            </el-col>
            <el-col :span="6" style="margin-left: 370px"
              ><div class="grid-content ep-bg-purple" />
              班次<el-select
                style="width: 520px"
                v-model="WorkCenterForm.classesData"
              >
                <el-option label="请选择" value="请选择" />
                <el-option label="晚班" value="晚班" />
                <el-option label="白班" value="白班" />
              </el-select>
            </el-col>
            <el-col :span="6" style="margin-left: 370px; margin-top: 10px"
              ><div class="grid-content ep-bg-purple" />
              状态<el-select
                style="width: 520px"
                v-model="WorkCenterForm.workCenterState"
              >
                <el-option label="有效" :value="true" />
                <el-option label="无效" :value="false" />
              </el-select>
            </el-col>
            <el-col :span="6" style="margin-left: 1000px; margin-top: 10px"
              ><div class="grid-content ep-bg-purple" />
              <el-button
                type="primary"
                style="width: 90px; margin-top: 20px"
                v-show="route.query.workCenterId == null"
                @click="CanIAddIt()"
                >保存</el-button
              >
              <el-button
                type="primary"
                style="width: 90px; margin-top: 20px"
                v-show="route.query.workCenterId != null"
                @click="WorkCenterUpdate()"
                >修改</el-button
              >
              <el-button
                style="margin-top: 20px; width: 80px"
                v-show="isshow"
                @click="AddWorkCenterInfo()"
                >{{ Wenzi }}</el-button
              >
            </el-col>
          </el-row>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
  <!-- 资源分配行的新增 -->
  <div style="background-color: #fff; height: 400px">
    <span
      style="
        text-align: center;
        color: dimgray;
        font-size: 20px;
        font-weight: 600;
      "
      >资源分配行</span
    >
    <hr style="margin: 15px 0 10px 0" />
    <span style="margin-left: 10px; color: dimgray">行信息</span>

    <br />
    <el-button
      type="primary"
      style="float: right; margin: 2px 0 10px 10px"
      @click="WorkCenterWealthFormVisible = true"
      >+分配资源</el-button
    >
    <el-dialog
      v-model="WorkCenterWealthFormVisible"
      title="资源分配编辑"
      width="500"
    >
      <el-form :model="WorkCenterWealthForm">
        <el-form-item label="资源">
          <el-select v-model="WorkCenterWealthForm.workCenterWealthIda">
            <el-option label="请选择" :value="0" />
            <el-option
              v-for="item in LoadResourceData"
              :label="item.resourceName"
              :value="item.resourceId"
              :key="item.resourceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可用数量">
          <el-input v-model="WorkCenterWealthForma.usableNum" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="WorkCenterWealthForm.abstract" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="WorkCenterWealthForm.workCenterWealthState">
            <el-option label="有效" :value="true" />
            <el-option label="无效" :value="false" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="WorkCenterWealthAdd()">确定</el-button>
          <el-button
            type="primary"
            @click="WorkCenterWealthFormVisible = false"
          >
            返回
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-table :data="WorkCenterWealthData" style="width: 100%">
      <el-table-column prop="workCenterWealthId" label="序号" />
      <el-table-column prop="resourceId" label="资源Id" />
      <el-table-column prop="usableNum" label="可用数量" />
      <el-table-column prop="createTime" label="创建时间">
        <template #default="{ row }">
          {{ Moment(row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="createName" label="创建人" />
      <el-table-column prop="workCenterWealthState" label="状态">
        <template #default="{ row }">
          {{ row.workCenterWealthState ? "有效" : "无效" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <!-- 添加时的假删除 -->
          <el-button
            v-show="route.query.workCenterId == null"
            type="danger"
            @click="WorkCenterWealthDelete(row)"
            >删除</el-button
          >
          <!-- 修改时的逻辑删除 -->
          <el-button
            v-show="route.query.workCenterId != null"
            type="danger"
            @click="WorkCenterWealthDeleteA(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import Moment from "moment";
//资源分配编辑对话框显示
const WorkCenterWealthFormVisible = ref(false);
const router = useRouter();
const route = useRoute();
import axios from "axios";
import { ref, reactive, onMounted, useId } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { mutable } from "element-plus/es/utils/typescript.mjs";
const fanhui = ref("< 返回");

//获取登录信息
const UserList = ref([]);
const LoadUserJSONData = () => {
  //读出数据
  const value = localStorage.getItem("userInfo");
  //反序列化JSON字符串
  UserList.value = JSON.parse(value);
  UserList.value.forEach((item: any) => {
    WorkCenterWealthForm.createName = item.userName;
    WorkCenterForm.createName = item.userName;
  });
};

//生产管理显示Url获取
const ProductionShowUrl = import.meta.env.VITE_APP_API_URL_ProductionShow;
//生产管理新增Url
const ProductionAddUrl = import.meta.env.VITE_APP_API_URL_ProductionAdd;
//企业添加信息Url获取
//const EnterpriseAdd = import.meta.env.VITE_APP_API_URL_EnterpriseAdd;
//资源行Form
const WorkCenterWealthForm = reactive({
  workCenterWealthId: 0,
  workCenterId: 0,
  //获取id
  workCenterWealthIda: 0,
  //无添加，后台进行查询添加信息
  workCenterWealthNum: "",
  //无添加，后台进行查询添加信息
  workCenterWealthName: "",
  usableNum: 0,
  abstract: "",
  //状态
  workCenterWealthState: true,
  createTime: new Date(),
  createName: "",
  isDelWorkCenterWealth: false,
  id: route.query.workCenterId,
});
//资源行辅助性Form
const WorkCenterWealthForma = reactive({
  usableNum: "",
});
//弹出层资源的下拉框绑定
const LoadResourceData: any = ref([]);
const LoadResource = () => {
  const data = {};
  axios
    .post(ProductionShowUrl + "/api/W/ResourceShowData", data)
    .then((res: any) => {
      console.log(res.data);
      LoadResourceData.value = res.data.data;
    });
};
//添加资源分配行的信息暂存到数组中
const WorkCenterWealthData: any = ref([]);
const IdNo = ref(0);
//添加资源分配行的信息
const WorkCenterWealthAdd = () => {
  if (WorkCenterWealthForma.usableNum == "") {
    ElMessage.error("请输入可用数量");
    return;
  }
  IdNo.value = IdNo.value + 1;
  const data = {
    workCenterWealthId: IdNo.value,
    workCenterId: WorkCenterWealthForm.workCenterId,
    resourceId: WorkCenterWealthForm.workCenterWealthIda,
    workCenterWealthIda: WorkCenterWealthForm.workCenterWealthIda,
    workCenterWealthNum: WorkCenterWealthForm.workCenterWealthNum,
    workCenterWealthName: WorkCenterWealthForm.workCenterWealthName,
    usableNum: Number(WorkCenterWealthForma.usableNum),
    abstract: WorkCenterWealthForm.abstract,
    workCenterWealthState: WorkCenterWealthForm.workCenterWealthState,
    createTime: WorkCenterWealthForm.createTime,
    createName: WorkCenterWealthForm.createName,
    isDelWorkCenterWealth: WorkCenterWealthForm.isDelWorkCenterWealth,
  };
  WorkCenterWealthFormVisible.value = false;
  WorkCenterWealthData.value.push(data);
};
//删除资源分配行里的信息（假删除因为该信息还没有进行添加）
const WorkCenterWealthDelete = (row: any) => {
  ElMessageBox.confirm("确认删除？", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log(row);
      //删除
      WorkCenterWealthData.value = WorkCenterWealthData.value.filter(
        (item: any) => item.workCenterWealthId !== row.workCenterWealthId
      );
      ElMessage({
        type: "success",
        message: "删除成功！！！",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败！！！",
      });
    });
};
//资源管理行信息 （逻辑删除 真删除 修改后台 IsDelete 状态为  true）
const WorkCenterWealthDeleteA = (row: any) => {
  ElMessageBox.confirm("确认删除？", "Warning", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      console.log(row);
      const data = {
        Id: row.workCenterWealthId,
      };
      //删除
      axios
        .post(
          ProductionAddUrl + "/api/WorkCenter/workCentersWealthDeleteData",
          data
        )
        .then((res: any) => {
          console.log(res.data);
          if (res.data.code > 0) {
            ElMessage({
              type: "success",
              message: "删除成功！！！",
            });
            GetWorkCenterWealthData();
          } else {
            ElMessage({
              type: "info",
              message: "删除失败！！！",
            });
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败！！！",
      });
    });
};
//根据工作中心id获取工作中心反填及资源行信息
const GetWorkCenterWealthData = () => {
  const data = {
    workCenterId: WorkCenterWealthForm.id,
  };
  axios
    .post(ProductionAddUrl + "/api/WorkCenter/WorkCenterReverseData", data)
    .then((res: any) => {
      console.log(res.data.data);
      //反填资源行的信息
      WorkCenterWealthData.value = res.data.data.list;
      //反填工作中心的信息
      WorkCenterForm.workCenterNum =
        res.data.data.workCenterres[0].workCenterNum;
      WorkCenterForm.workCenterName =
        res.data.data.workCenterres[0].workCenterName;
      WorkCenterForm.workCenterType =
        res.data.data.workCenterres[0].workCenterType;
      WorkCenterForm.classesData = res.data.data.workCenterres[0].classesData;
      WorkCenterForm.workCenterState =
        res.data.data.workCenterres[0].workCenterState;
    });
};

//显示提交按钮
const isshow = ref(false);
//工作中心编码是否只读
const isno = ref(false);
const Wenzi = ref("提交 >");
//工作中心Form
const WorkCenterForm = reactive({
  workCenterId: 0,
  workCenterNum: "",
  workCenterName: "",
  workCenterType: "请选择",
  classesData: "请选择",
  createTime: new Date(),
  createName: "",
  workCenterState: true,
  approvalState: 0,
  isDelWorkCenter: false,
});

//判断是否可以进行下一步操作
const CanIAddIt = () => {
  if (WorkCenterForm.workCenterNum == "") {
    ElMessage.error("请输入工作中心编号");
    return;
  }
  if (WorkCenterForm.workCenterName == "") {
    ElMessage.error("请输入工作中心名称");
    return;
  }
  if (WorkCenterForm.workCenterType == "请选择") {
    ElMessage.error("请选择工作中心类型");
    return;
  }
  if (WorkCenterForm.classesData == "请选择") {
    ElMessage.error("请选择班次");
    return;
  }
  isshow.value = true;
  isno.value = true;
};

const aaa = import.meta.env.VITE_APP_API_URL_StartWorkflowData;
const userId = ref(0);
//添加工作中心信息
const AddWorkCenterInfo = () => {
  if (WorkCenterWealthForm.workCenterWealthIda == 0) {
    ElMessage.error("请完善资源分配行信息，请选择工作中心资源");
    return;
  }
  if (WorkCenterWealthForma.usableNum == "") {
    ElMessage.error("请完善资源分配行信息，请输入可用数量");
    return;
  }
  if (WorkCenterWealthForm.abstract == "") {
    ElMessage.error("请完善资源分配行信息，请输入摘要");
    return;
  }
  const data = {
    workCenterId: 0,
    workCenterNum: WorkCenterForm.workCenterNum,
    workCenterName: WorkCenterForm.workCenterName,
    workCenterType: WorkCenterForm.workCenterType,
    classesData: WorkCenterForm.classesData,
    createTime: WorkCenterForm.createTime,
    createName: WorkCenterForm.createName,
    workCenterState: WorkCenterForm.workCenterState,
    approvalState: WorkCenterForm.approvalState,
    isDelWorkCenter: WorkCenterForm.isDelWorkCenter,
    WorkCenterWealthData: WorkCenterWealthData.value,
  };
  axios
    .post(ProductionAddUrl + "/api/WorkCenter/WorkCenterAddData", data)
    .then((res: any) => {
      console.log(res.data);
      if (res.data.code > 0) {
        ElMessage.success(res.data.msg);
        if (WorkCenterForm.createName == "MaxAdmin") {
          userId.value = 1;
          WorkCenterForm.createName = "MaxAdmin";
        } else if (WorkCenterForm.createName == "admin") {
          userId.value = 2;
          WorkCenterForm.createName = "admin";
        } else if (WorkCenterForm.createName == "李四") {
          userId.value = 4;
          WorkCenterForm.createName = "李四";
        } else {
          userId.value = 0;
          WorkCenterForm.createName = "";
        }
        //添加审批信息
        const DataList = {
          workflowDefinitionId: "WorkCenter01",
          title: "工作中心任务",
          formContent: WorkCenterForm.workCenterNum,
          version: 1,
          userId: userId.value,
          userName: WorkCenterForm.createName,
          workflowId: "",
        };
        axios
          .post(aaa + "/api/Workflow/StartWorkflowData", DataList)
          .then((res: any) => {
            console.log(res.data);
            if (res.data.code > 0) {
              ElMessage.success("审批信息添加成功，编号为：" + res.data.msg);
              //存入数据
              localStorage.setItem("workflowIda", res.data.msg);
            } else {
              ElMessage.error("审批信息添加失败");
            }
          });
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};
//修改工作中心信息
const WorkCenterUpdate = () => {
  const data = {
    workCenterId: WorkCenterWealthForm.id,
    workCenterNum: WorkCenterForm.workCenterNum,
    workCenterName: WorkCenterForm.workCenterName,
    workCenterType: WorkCenterForm.workCenterType,
    classesData: WorkCenterForm.classesData,
    createTime: new Date(),
    createName: WorkCenterForm.createName,
    workCenterState: WorkCenterForm.workCenterState,
    approvalState: WorkCenterForm.approvalState,
    isDelWorkCenter: WorkCenterForm.isDelWorkCenter,
  };
  axios
    .post(ProductionAddUrl + "/api/WorkCenter/WorkCenterUpdData", data)
    .then((res: any) => {
      console.log(res.data.data);
      if (res.data.code > 0) {
        ElMessage.success(res.data.msg);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};
//页面初始化
onMounted(() => {
  LoadResource();
  LoadUserJSONData();
  GetWorkCenterWealthData();
  if (Number(WorkCenterWealthForm.id) > 0) {
    GetWorkCenterWealthData();
  }
});
</script>

<style scoped></style>
